package leetcode.code0164;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public int maximumGap(int[] nums) {
		int max = Integer.MIN_VALUE;
		for (int num : nums) {
			max = Math.max(max, num);
		}
		int base = 1;
		int len = nums.length;
		int[] buf = new int[len];
		while (base <= max) {
			int[] bucket = new int[10];
			for (int num : nums) {
				int idx = num / base % 10;
				bucket[idx] += 1;
			}
			int sum = 0;
			for (int i = 9; i >= 0; i--) {
				sum += bucket[i];
				bucket[i] = len - sum;
			}
			for (int num : nums) {
				int idx = num / base % 10;
				buf[bucket[idx]] = num;
				bucket[idx]++;
			}
			nums = Arrays.copyOf(buf, len);
			base *= 10;
		}
		int ans = 0;
		for (int i = 1; i < len; i++) {
			ans = Math.max(ans, nums[i] - nums[i - 1]);
		}
		return ans;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(5, this.maximumGap(HelpDebug.str2array3("[4,0,10,5]")));

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub
		HelpDebug.compare(3, this.maximumGap(HelpDebug.str2array3("[3,6,9,1]")));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub
		HelpDebug.compare(0, this.maximumGap(HelpDebug.str2array3("[5]")));
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
